<?php # IR - 2011

require_once '../mysqlConnect.php';

if (!isset($_POST['id']) || !isset($_POST['record_date']) || !isset($_POST['answer'])) {
	echo "fail";
	die();
}
else {
	
	$id = $_POST['id'];
	$record_date = $_POST['record_date'][1];
	$answers = $_POST['answer'];
	
	$sql_retrieve_column_names = "SHOW COLUMNS FROM neuropsychological_symptom_answers";
	$conn = GetConnection();
	if ($conn->connect_errno != 0) {
		echo "fail";
		$conn->close();
		die();
	}
	
	$results = $conn->query($sql_retrieve_column_names);
	if ($conn->errno != 0) {
		echo "fail";
		$conn->close();
		die();
	}
	
	$names = array();
	while ($rs = $results->fetch_assoc()) {
		$names[] = $rs['Field'];
	}
	unset($names[0]); # id
	unset($names[1]); # patientId
	unset($names[count($names) + 1]); # record_date
	$names = array_values($names); # reset keys in array
	
	$sql = null;
	# for every row in the names array, retrieve the answer to the question from the page 
	for ($i = 0; $i < count($names); $i++) {
		$int = substr($names[$i], 7);
		foreach($answers as $key => $value) {
			if ($value[0] == $int)
				$sql .= "UPDATE neuropsychological_symptom_answers SET qnumber" . $int . " = '" . $value[1] . "' WHERE id = " . $id . "LIMIT 1;\n";				
		}
	}
	
	$conn->multi_query($sql);
	
	if ($conn->errno != 0) {
		echo "fail";
		$conn->close();
		die();
	}
	
	echo "success";
	$conn->close();
}